<template>
  <view class="content">
    <view style="background-color: #fff;">
      <u-cell-group>
        <u-cell title="取货方式" titleStyle="color: #a3a3a3; font-size: 36rpx;">
          <template v-slot:value>
            <view class="logisticsTypeWrap">
              <view @click="editLogisticsType(1)" :class="logisticsType === 1 ? 'logisticsTypeActive logisticsTypeItem' : 'logisticsTypeItem'">邮寄</view>
              <view style="width: 1rpx;height: 100%;background-color: #f2f2f2"/>
              <view @click="editLogisticsType(2)" :class="logisticsType === 2 ? 'logisticsTypeActive logisticsTypeItem' : 'logisticsTypeItem'">自提</view>
            </view>
          </template>
        </u-cell>
      </u-cell-group>
    </view>
    <view class="locationWrap" @click="selectAddr" v-if="logisticsType === 1">
      <view class="locationIcon">
        <u-icon name="map" color="#79C435" size="36"></u-icon>
      </view>
      <view style="width: 100%; padding: 0 16rpx">
         <view v-if="addressObj?.id">
          <up-text type="" color="#000" size="36" :text="`${addressObj?.province || ''}${addressObj?.city || ''}${addressObj?.area || ''}${addressObj?.detail || ''}`" :lines="1"></up-text>
        </view>
        <view v-else>
          <up-text type="" color="#999" size="36" text="请选择地址" :lines="2"></up-text>
        </view>
      </view>
      <u-icon name="arrow-right" color="#999" size="36"></u-icon>
    </view>
    <u-gap height="24" bgColor="#f2f2f2"></u-gap>
    <view v-for="item in productList" class="productItem" :key="item.id">
      <view style="height: 176rpx; width: 176rpx;">
         <u-image height="176rpx" width="176rpx" :src="item.detail.goodsPic" :lazy-load="true" mode="aspectFit"></u-image>
      </view>
      <view style="flex: 1; margin: 0 24rpx;">
        <up-text type="" color="#000" size="36" :text="item.detail.name" :bold="true" :lines="2"></up-text>
        <up-text size="28" type="" color="#a3a3a3" :text="item.detail.description" :lines="2" margin="24rpx 0 0"></up-text>
      </view>
      <view style="display: flex; flex-direction: column; align-items: flex-end;">
        <view>
          <up-text type="" color="#000" size="28" :text="`¥ ${priceFormatPrice(item.detail.price)}`" ></up-text>
        </view>
        <view style="margin-top: 24rpx;">
          <up-text type="" size="28" color="#a3a3a3" :text="`x ${item.num}`" ></up-text>
        </view>
      </view>
    </view>
    <u-gap height="24" bgColor="#f2f2f2"></u-gap>
    <view style="background-color: #fff;">
      <u-cell-group>
        <u-cell title="产品金额" titleStyle="color: #a3a3a3; font-size: 36rpx;">
          <template v-slot:value>
            <view>
              <up-text type="" color="#000" size="36" :text="price" :bold="true"></up-text>
            </view>
          </template>
        </u-cell>
        <u-cell title="物流费用" titleStyle="color: #a3a3a3; font-size: 36rpx;">
          <template v-slot:value>
            <view>
              <up-text type="" color="#000" size="36" :text="logisticsPrice" :bold="true"></up-text>
            </view>
          </template>
        </u-cell>
        <u-cell title="订单总金额" titleStyle="color: #a3a3a3; font-size: 36rpx;">
          <template v-slot:value>
            <view>
              <up-text type="" color="#000" size="36" :text="totalPrice" :bold="true"></up-text>
            </view>
          </template>
        </u-cell>
      </u-cell-group>
    </view>
    <u-gap height="200" bgColor="#f2f2f2"></u-gap>
    <view class="row between bottomWrap">
      <view class="row" style="width: 100%">
        <view style="margin-left: 30rpx;">
          <up-text type="" color="#000" size="28" text="共"></up-text>
        </view>
        <view style="margin: 0 8rpx;">
          <up-text type="" color="#000" size="28" :bold="true" :text="allNum"></up-text>
        </view>
        <view>
          <up-text type="" color="#000" size="28" text="件"></up-text>
        </view>
        <view style="margin-left: 16rpx; flex-shrink: 0;">
          <up-text type="" color="#000" size="28" text="实付"></up-text>
        </view>
        <view style="width: 100%; margin-left: 16rpx;">
          <view class="row" style="align-items: center;">
            <view>
              <up-text type="" color="#000" size="28" text="积分："></up-text>
            </view>
            <view>
              <up-text size="36" :bold="true" type="" color="#59B235" :text="point"></up-text>
            </view>
          </view>
          <view class="row" style="align-items: center;">
            <view>
              <up-text type="" color="#000" size="28" text="其他积分："></up-text>
            </view>
            <view>
              <up-text size="36" :bold="true" type="" color="#59B235" :text="realPoint"></up-text>
            </view>
          </view>
        </view>
      </view>
      <view style="width: 240rpx; height: 100%; background-color: #79C435; display: flex; align-items: center; justify-content: center; flex-shrink: 0;" @click="show = true">
        <view>
          <up-text text="提交订单" type="" color="#fff" :bold="true" size="36"></up-text>
        </view>
      </view>
    </view>
  </view>
  <up-modal :show="show" :showCancelButton="true" confirmColor="#79C435" @cancel="show=false" @confirm="sure">
    <up-text text="确认支付" type="" color="#000" size="30" align="center"></up-text>
  </up-modal>
  <up-toast ref="uToastRef"></up-toast>
  <u-toast ref="uToast"></u-toast>
</template>

<script>
import { addOrder } from '@/services/shop';
import { editUser } from '@/services/user';
import { getAddressList } from '@/services/address';
import { store } from '@/store';
import { orderPayResult, commitOrder } from '@/services/order';
import { getUserInfo, provinceList } from '@/utils/common';

export default {
  data() {
    return {
      productList: [],
      iconStyle: {
        marginRight: '-13px',
      },
      titleStyle: {
        color: '#101010',
        marginLeft: '-13px',
      },
      payOrderId: '',
      totalPrice: '',
      price: '',
      logisticsPrice: '',
      point: '',
      realPoint: '',
      show: false,
      addr: '',
      addressObj: {},
      logisticsType: 1,
    }
  },
  onLoad(option) {
    const _that = this;
    const eventChannel = this.getOpenerEventChannel();
    Promise.all([
      new Promise((resolve) => {
        getAddressList().then((res) => {
          console.log('getAddressList', res);
          if (res?.data?.length) {
            const obj = res.data.find((item) => `${item.isDefault}` === "1") ||  {};
            if (obj) {
              _that.addressObj = obj;
            }
          }
        }).finally(() => {
          resolve('getAddressList')
        })
      }),
      new Promise((resolve) => {
        eventChannel.on('orderConfirmation', ({ data }) => {
          console.log('orderConfirmation', data)
          _that.productList = data;
          resolve('orderConfirmation')
        })
      })
    ]).finally(() => {
      _that.getPrice();
    })
  },
  computed: {
    isPoint() {
      const { isPoint } = this.$store.state;
      return isPoint;
    },
    allNum() {
      let allNum = 0;
      this.productList.forEach(({ num }) => {
        allNum += num;
      })
      return allNum;
    },
    orderPrice() {
      let allPrice = 0;
      this.productList.forEach(({ detail, num }) => {
        const { price } = detail;
        allPrice += price * num;
      })
      if (uni.$u.test.amount(allPrice)) {
        return '¥' + this.priceFormatPrice(allPrice);
      }
      return '¥0.00';
    }
  },
  onShow() {
    this.getPrice();
    if (this.payOrderId) {
      this.payResult(this.payOrderId);
    }
  },
  beforeUnmount() {
    this.timer && clearTimeout(this.timer);
  },
  methods: {
    editLogisticsType(type) {
      this.logisticsType = type;
      this.getPrice();
    },
    getPrice() {
      const { addressObj, productList, logisticsType } = this;
      console.log('addressObj', addressObj)
      console.log('productList', productList)
      if (!addressObj?.id && logisticsType === 1) {
        this.totalPrice = '¥ 0.00';
        this.price = '¥ 0.00';
        this.logisticsPrice = '¥ 0.00';
        this.point = 0;
        this.realPoint = 0;
        return;
      };
      if (!productList?.length) return;
      const _that = this;
      _that.$refs.uToastRef.show({
        type: 'loading',
        message: "订单价格计算中...",
        duration: -1
      });
      const params = {
        logisticsType,
        modelRequestList: productList.map(({ detail, num }) => {
          const {goodsId} = detail || {};
          return {
            goodsId,
            num,
          }
        })
      }
      if (logisticsType === 1) {
        params.addrId = addressObj.id;
      }
      commitOrder(params).then((res) => {
        const { totalPrice, price, logisticsPrice, point, realPoint } = res?.data || {};
        this.$refs.uToastRef.hide();
        if (res.success) {
          _that.totalPrice = `¥ ${totalPrice || 0.00}`;
          _that.price = `¥ ${price || 0.00}`;
          _that.logisticsPrice = `¥ ${logisticsPrice || 0.00}`;
          _that.point = point;
          _that.realPoint = realPoint;
        } else {
          _that.$refs.uToastRef.show({
            type: 'error',
            message: "订单价格获取失败",
            duration: 3000
          })
        }
      }).catch(() => {
        this.$refs.uToastRef.hide();
      })
    },
    selectAddr() {
      const _that = this;
      // uni.navigateTo({
      //   url: '/pages/address/select',
      //   events: {
      //     selectAddr: (addr) => {
      //        _that.addr = addr;
      //     }
      //   },
      // });
      uni.navigateTo({
        url: '/pages/address/index',
        events: {
          selectAddress: (data) => {
            console.log('selectAddress', data);
            this.addressObj = data;
            uni.navigateBack({ delta: 1 });
          },
          addressBack: () => {
            if (this.addressObj.id) {
              const _that = this;
              getAddressList().then((res) => {
                if (res?.data?.length && _that.addressObj.id) {
                  const obj = res.data.find((item) => `${item.id}` === `${_that.addressObj.id}`) ||  {};
                  if (obj) {
                    _that.addressObj = obj;
                  }
                }
              })
            }
          },
          deleteAddress: (id) => {
            if (this.addressObj.id === id) {
              this.addressObj = {};
            }
          }
        }
      })
    },
    priceFormatPrice (price) {
      return uni.$u.priceFormat(price, '2', '.', ',');
    },
    payResult(tradeNo) {
      const _that = this;
      const goOrderList = () => {
        _that.timer = setTimeout(() => {
          uni.redirectTo({
            url: `/pages/orderInfo/index?tradeNo=${tradeNo}`,
          })
        }, 1500)
      }
      orderPayResult({
        tradeNo
      }).then(({ data, success }) => {
        if (success && data) {
         this.$refs.uToastRef.show({
            type: 'default',
            message: '订单支付成功',
            duration: 3000
          })
          goOrderList();
        } else {
          this.$refs.uToastRef.show({
            type: 'error',
            message: '订单支付失败',
            duration: 3000
          })
        }
      })
    },
    async sure() {
      const _that = this;
      this.show = false;
      const { productList, addressObj, logisticsType } = this;
      if (!addressObj?.id && logisticsType === 1) {
        this.$refs.uToast.show({
          message: "请填写地址",
        })
        return;
      }
      this.$refs.uToastRef.show({
        type: 'loading',
        title: '正在加载',
        message: "订单生成中...",
        duration: -1
      })
      const params = {
        modelRequestList: productList.map(({ detail, num }) => {
          const {goodsId} = detail || {};
          return {
            goodsId,
            num,
          }
        }),
        logisticsType,
      }
      if (logisticsType === 1) {
        params.addrId = addressObj.id;
      }
      const res = await addOrder(params);
      this.$refs.uToastRef.hide();
      if (res.success) {
        const { outTradeNo, response } = res?.data || {};
        this.$refs.uToastRef.show({
          type: 'default',
          message: "订单生成成功",
          duration: 3000
        });
        const goOrderList = () => {
          _that.timer = setTimeout(() => {
            uni.redirectTo({
              url: `/pages/orderInfo/index?tradeNo=${outTradeNo}`,
            })
          }, 1500)
        }
        if (_that.isPoint) {
          goOrderList();
        } else {
          wx.requestPayment({
            ...response,
            package: response.packageVal,
            success: async (success) => {
              _that.payOrderId = outTradeNo;
              _that.payResult(outTradeNo);
            },
            fail: (fail) => {
              console.log('fail', fail);
              this.$refs.uToastRef.show({
                type: 'error',
                message: '订单支付失败',
                duration: 3000
              })
            },
          })
        }
      } else {
        this.$refs.uToastRef.show({
          type: 'default',
          message: res.errorMessage || '订单生成失败',
          duration: 3000
        })
      }
    },
  }
}
</script>

<style lang="scss" scoped>
.content {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f2f2f2;
}

.locationWrap {
  padding: 24rpx 30rpx;
  display: flex;
  flex-direction: row;
  align-items: center;
  background-color: #fff;
}

.locationIcon {
  height: 88rpx;
  width: 88rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #EEF9E6;
  flex-shrink: 0;
}

.productItem {
  padding: 24rpx 30rpx;
  display: flex;
  flex-direction: row;
  background-color: #fff;
}

.bottomWrap{
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  align-items: center;
  height: 108rpx;
  border-top: 1rpx solid #f2f2f2;
  background-color: #fff;
  padding-bottom: calc(env(safe-area-inset-bottom) / 2);
}

.inputWrap {
  width: 100%;
  font-size: 30rpx;
  padding: 0 16rpx;
  line-height: 88rpx;
  height: 88rpx;
}

.logisticsTypeWrap {
  height: 72rpx;
  border: 1rpx solid #f2f2f2;
  display: flex;
  flex-direction: row;
}

.logisticsTypeItem {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  width: 120rpx;
  font-size: 28rpx;
}

.logisticsTypeActive {
  background-color: #79C435;
  color: #fff;
}

</style>
